package com.runa.protocol.enums;

public enum ModbusFunctionCode {

    READ_COILS(1),//读线圈状态
    READ_INPUTS(2),//读输入状态
    READ_HOLDING_REGISTERS(3),//读保持寄存器
    READ_INPUT_REGISTERS(4),//读输入寄存器
    WRITE_COIL(5),//强制单个线圈
    WRITE_REGISTER(6),//预置单个寄存器
    WRITE_COILS(15),//强制多个线圈
    WRITE_REGISTERS(16);//预置多个寄存器

    private byte _code;
    ModbusFunctionCode(int code){
        _code = (byte)code;
    }

    public byte getFunctionCode(){
        return _code;
    }

    /**
     * 获取功能对应的寄存器地址类型
     * @return
     */
    public int getRegistersType(){
        int type = -1;
        switch(_code){
            case 1:
            case 5:
            case 15:
                type = 0;
                break;
            case 2:
                type = 1;
                break;
            case 3:
            case 6:
            case 16:
                type = 4;
                break;
            case 4:
                type = 3;
                break;
        }
        return type;
    }

    public static ModbusFunctionCode getByCode(int bt) {
        ModbusFunctionCode code = null;
        switch (bt){
            case 1:
                code = READ_COILS;
                break;
            case 2:
                code = READ_INPUTS;
                break;
            case 3:
                code = READ_HOLDING_REGISTERS;
                break;
            case 4:
                code = READ_INPUT_REGISTERS;
                break;
            case 5:
                code = WRITE_COIL;
                break;
            case 6:
                code = WRITE_REGISTER;
                break;
            case 15:
                code = WRITE_COILS;
                break;
            case 16:
                code = WRITE_REGISTERS;
                break;
        }
        return code;
    }

    public boolean isReadOrWrite() {
        switch (_code) {
            case 1:
            case 2:
            case 3:
            case 4:
                return true;
            case 5:
            case 6:
            case 15:
            case 16:
                return false;
                default:
                    return false;
        }
    }

}
